package com.spice.service.util;

import cn.hutool.core.io.FileUtil;
import com.spice.common.exception.SpiceException;
import com.spice.service.entity.pojo.FileInfo;
import com.spice.service.entity.pojo.ImageInfo;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.LinkOption;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.BasicFileAttributeView;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.*;

public class MultipartFileUtil {
    public static File saveFileFolder = new File("resources/files/");
    public static final List<String> ALLOW_IMAGE_TYPES = Arrays.asList("image/jpeg", "image/png");

    public static File[] getFiles() {
        return FileUtil.ls(saveFileFolder.getAbsolutePath());
    }

    public static Date getCreateTime(String localFileName) {
        Path path = Paths.get(new File(saveFileFolder, localFileName).getAbsolutePath());
        BasicFileAttributeView basicview = Files.getFileAttributeView(path, BasicFileAttributeView.class, LinkOption.NOFOLLOW_LINKS);
        BasicFileAttributes attr;
        try {
            attr = basicview.readAttributes();
            Date createDate = new Date(attr.creationTime().toMillis());
            return createDate;
        } catch (Exception e) {
            e.printStackTrace();
        }
        Calendar cal = Calendar.getInstance();
        cal.set(1970, 0, 1, 0, 0, 0);
        return cal.getTime();
    }

    public static void download(String filename, HttpServletResponse res) throws IOException {
        // 发送给客户端的数据
        OutputStream outputStream = res.getOutputStream();
        byte[] buff = new byte[1024];
        BufferedInputStream bis = null;
        // 读取filename
        bis = new BufferedInputStream(new FileInputStream(new File("./resources/files/" + filename)));
        int i = bis.read(buff);
        while (i != -1) {
            outputStream.write(buff, 0, buff.length);
            outputStream.flush();
            i = bis.read(buff);
        }
    }


    public static void initializeDirectory() {
        if (!saveFileFolder.isDirectory()) {
            saveFileFolder.mkdirs();
        }
    }

    public static boolean isImage(MultipartFile file) {
        // 1.文件校验
        if (file == null) {
            // 图片不存在
            return false;
        }
        // 2.后缀名校验
        String contentType = file.getContentType();
        if (!ALLOW_IMAGE_TYPES.contains(contentType)) {
            // 后缀不对
            return false;
        }
        // 3.内容校验
        try {
            BufferedImage image = ImageIO.read(file.getInputStream());
            if (image == null) {
                // 图片格式不正确
                return false;
            } else {
                return true;
            }
        } catch (IOException e) {
            return false;
        }
    }

    public static FileInfo saveFile(MultipartFile file) {
        initializeDirectory();
        String newName = generateNewFilename(Objects.requireNonNull(file.getOriginalFilename()));
        try {
            file.transferTo(new File(saveFileFolder.getAbsolutePath(), newName));
            return new FileInfo(file.getOriginalFilename(), newName);
        } catch (IOException e) {
            e.printStackTrace();
            throw new SpiceException().message("保存文件失败");
        }
    }

    public static ImageInfo saveImage(MultipartFile file) {
        initializeDirectory();
        String newName = generateNewFilename(Objects.requireNonNull(file.getOriginalFilename()));
        try {
            file.transferTo(new File(saveFileFolder.getAbsolutePath(), newName));
            return new ImageInfo(file.getOriginalFilename(), newName);
        } catch (IOException e) {
            e.printStackTrace();
            throw new SpiceException().message("上传文件失败");
        }
    }

    public static byte[] getFile(String fileName) throws IOException {
        File file = new File(saveFileFolder.getAbsolutePath() + "/" + fileName);
        FileInputStream inputStream = new FileInputStream(file);
        byte[] bytes = new byte[inputStream.available()];
        inputStream.read(bytes, 0, inputStream.available());
        return bytes;
    }

    public static boolean isFileExist(String fileName) {
        return new File(saveFileFolder.getAbsolutePath() + "/" + fileName).exists();
    }

    private static String generateNewFilename(String originalFilename) {
        String originalName = originalFilename.substring(0, originalFilename.lastIndexOf("."));
        if (originalName.length() > 64) {
            originalName = originalName.substring(0, 64) + "...";
        }
        return originalName
                + "_"
                + new Date().getTime()
                + "_"
                + UUID.randomUUID().toString().substring(0, 4)
                + originalFilename.substring(originalFilename.lastIndexOf("."));
    }
}


//    String url = request.getRequestURL().toString();
//    String fileContentUrl = url.substring(0, url.lastIndexOf('/')) + "/getFileContent/" + newName;
//    String imageUrl = url.substring(0, url.lastIndexOf('/')) + "/getImage/" + newName;
//    String downloadUrl = url.substring(0, url.lastIndexOf('/')) + "/downloadFile/" + newName;
//            return Response.ok()
//                    .data("fileName", newName)
//                    .data("fileContentUrl", fileContentUrl)
//                    .data("imageUrl", imageUrl)
//                    .data("downloadUrl", downloadUrl);
//             return Response.error();